﻿using System.IO;
using System.Web.Hosting;

namespace CoreEx.ServiceModel
{
    /// <summary>
    /// Represents a virtual .svc file.
    /// </summary>
    public class VirtualSvcFile : VirtualFile
    {
        private readonly string _serviceTypeName;

        private const string SvcTemplate = "<%@ ServiceHost Language=\"C#\" Debug=\"true\" Service=\"{0}\" Factory = \"{1}\" %>";
        /// <summary>
        /// Initializes a new instance of the <see cref="VirtualSvcFile"/> class.
        /// </summary>
        /// <param name="virtualPath">The virtual path to the resource represented by this instance.</param>
        /// <param name="serviceTypeName">The type name of the requested service.</param>
        public VirtualSvcFile(string virtualPath, string serviceTypeName)
            : base(virtualPath)
        {
            _serviceTypeName = serviceTypeName;
        }

        /// <summary>
        /// When overridden in a derived class, returns a read-only stream to the virtual resource.
        /// </summary>
        /// <returns>A read-only stream to the virtual file.</returns>
        public override Stream Open()
        {
            var memoryStream = new MemoryStream();
            var streamWriter = new StreamWriter(memoryStream);
            string svc = string.Format(SvcTemplate, _serviceTypeName,
                                       typeof(ServiceContainerServiceHostFactory).FullName);
            streamWriter.Write(svc);
            streamWriter.Flush();
            memoryStream.Seek(0, SeekOrigin.Begin);
            return memoryStream;
        }
    }
}